package com.o2o.controller.frontend;

import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.o2o.dto.ShopExecution;
import com.o2o.entity.*;
import com.o2o.service.*;
import com.o2o.utils.HttpServletRequestUtil;
import com.o2o.utils.QRCodeUtil;
import com.o2o.utils.baidu.ShortNetAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * package_name:com.o2o.controller.frontend
 * Author:徐亚远
 * Date:2019/12/23 10:43
 * 项目名:o2o
 * Desription:
 **/
@Controller
@RequestMapping("/frontend")
public class MainPageController {
    @Autowired
    private ShopService shopService;
    @Autowired
    private ShopCategoryservice shopCategoryservice;
    @Autowired
    private HeadLineService headLineService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private ProductService productService;

    private static String URLPREFIX = "https://open.weixin.qq.com/connect/oauth2/authorize?"
            + "appid=wxd7f6c5b8899fba83&"
            + "redirect_uri=115.28.159.6/myo2o/shop/adduserproductmap&"
            + "response_type=code&scope=snsapi_userinfo&state=";
    private static String URLSUFFIX = "#wechat_redirect";

    /*
    * 初始化前端展示系统的主页信息,包括获取一级店铺类别列表以及头条列表
    * @return
    * */
    @RequestMapping(value = "/listmainpageinfo",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> listMainPageInfo(){
        Map<String,Object> modelMap = new HashMap<>();
        List<ShopCategory> shopCategoryList = new ArrayList<>();
        try {
            //获取以及店铺类别列表(即parentId为空的ShopCategory)
            shopCategoryList = shopCategoryservice.getShopCategoryList(null);
            modelMap.put("shopCategoryList",shopCategoryList );
        }catch (Exception e){
            modelMap.put("success",false);
            modelMap.put("errMsg",e.getMessage() );
            return modelMap;
        }
        List<HeadLine> headLineList = new ArrayList<>();
        try {
            //获取状态为可用(1)的头条列表
            HeadLine headLineCondition = new HeadLine();
            headLineCondition.setEnableStatus(1);
            headLineList=headLineService.getHeadLineList(headLineCondition);
            modelMap.put("headLineList",headLineList );
        }catch (Exception e){
            modelMap.put("success",false );
            modelMap.put("errMsg",e.getMessage() );
            return modelMap;
        }
        modelMap.put("success",true);
        return modelMap;
    }
    /*
     * 返回商品列表页里的ShopCategory列表(二级或一级),以及区域信息列表
     * @param request
     * @return
     * */
    @RequestMapping(value = "/listshopspageinfo",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> listShopsPageInfo(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<>();
        //试着从前端请求中获取parentId
        Long parentId = HttpServletRequestUtil.getLong(request,"parentId" );
        List<ShopCategory> shopCategoryList = null;
        if (parentId != -1){
            //如果parentId存在,则取出该一级shopCategory下的二级ShopCategory列表
            try {
                ShopCategory shopCategoryCondition = new ShopCategory();
                ShopCategory parent = new ShopCategory();
                parent.setShopCategoryId(parentId);
                shopCategoryCondition.setParent(parent);
                shopCategoryList = shopCategoryservice.getShopCategoryList(shopCategoryCondition);
            }catch (Exception e){
                modelMap.put("success",false );
                modelMap.put("errMsg",e.getMessage() );
            }
        }else {
            try {
                //如果parentId不存在,则取出所有一级ShopCategory(用户在首页选择的是全部商品列表)
                shopCategoryList = shopCategoryservice.getShopCategoryList(null);
            }catch (Exception e){
                modelMap.put("success",false );
                modelMap.put("errMsg",e.getMessage() );
            }
        }
        modelMap.put("shopCategoryList",shopCategoryList );
        List<Area> areaList = null;
        try {
            //获取区域列表信息
            areaList = areaService.queryAll();
            modelMap.put("areaList",areaList );
            modelMap.put("success",true );
            return modelMap;
        }catch (Exception e){
            modelMap.put("success",false );
            modelMap.put("errMsg",e.getMessage() );
        }
        return modelMap;
    }

    /*
     *获取指定查询条件下的店铺列表
     * @param request
     * @return
     * */
    @RequestMapping(value = "/listshops",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> listShops(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<>();
        //获取页码
        int pageIndex = HttpServletRequestUtil.getInt(request,"pageIndex" );
        //获取一页需要显示的数据条数
        int pageSize = HttpServletRequestUtil.getInt(request,"pageSize" );
        //非空判断
        if ((pageIndex> -1)&&(pageSize >-1)){
            //试着获取一级类别Id
            long parentId = HttpServletRequestUtil.getLong(request,"parentId" );
            //试着获取特定二级类别Id
            long shopCategoryId = HttpServletRequestUtil.getInt(request,"shopCategoryId" );
            //试着获取区域Id
            int areaId = HttpServletRequestUtil.getInt(request,"areaId" );
            //试着获取模糊查询的名字
            String shopName = HttpServletRequestUtil.getString(request,"shopName" );
            //获取组合之后的查询条件
            Shop shopCondition = compactShopCondition4Search(parentId,shopCategoryId,areaId,shopName);
            //根据查询条件和分页信息获取店铺列表,并返回总数
            ShopExecution se = shopService.getShopList(shopCondition,pageIndex ,pageSize );
            modelMap.put("shopList",se.getShopList() );
            modelMap.put("count",se.getCount() );
            modelMap.put("success",true);
        }else {
            modelMap.put("success",false );
            modelMap.put("errMsg","empty pageSize or pageIndex" );
        }
        return modelMap;
    }

    /*
     * 组合条件查询,并将其条件封装到ShopCondition对象里返回
     * @param parentId
     * @param shopCategoryId
     * @param areaId
     * @param shopName
     * @return
     *
     * */
    private Shop compactShopCondition4Search(long parentId, long shopCategoryId, int areaId, String shopName){
        Shop shopCondition = new Shop();
        if (parentId !=-1L){
            //查询某个一级ShopCategory下面的所有二级ShopCategory里面的店铺列表
            ShopCategory childCategory = new ShopCategory();
            ShopCategory parentCategory = new ShopCategory();
            parentCategory.setShopCategoryId(parentId);
            childCategory.setParent(parentCategory);
            shopCondition.setShopCategory(childCategory);
        }
        if (shopCategoryId !=-1L){
            //查询某个二级ShopCategory下面的店铺列表
            ShopCategory shopCategory = new ShopCategory();
            shopCategory.setShopCategoryId(shopCategoryId);
            shopCondition.setShopCategory(shopCategory);
        }
        if (areaId!=-1L){
            //查询某个区域Id下的店铺列表
            Area area = new Area();
            area.setAreaId(areaId);
            shopCondition.setArea(area);
        }
        if (shopName !=null){
            //查询名字里包含shopName的店铺列表
            shopCondition.setShopName(shopName);
        }
        //前端展示的店铺都是审核成功的店铺
        shopCondition.setEnableStatus(1);
        return shopCondition;
    }

    @RequestMapping(value = "/listproductdetailpageinfo", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> listProductDetailPageInfo(
            HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        long productId = HttpServletRequestUtil.getLong(request, "productId");
        Product product = null;
        if (productId != -1) {
            product = productService.getProductById(productId);
            modelMap.put("product", product);
            modelMap.put("success", true);
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "empty productId");
        }
        return modelMap;
    }

    @RequestMapping(value = "/generateqrcode4product", method = RequestMethod.GET)
    @ResponseBody
    private void generateQRCode4Product(HttpServletRequest request,
                                        HttpServletResponse response) {
        long productId = HttpServletRequestUtil.getLong(request, "productId");
        PersonInfo user = (PersonInfo) request.getSession()
                .getAttribute("user");
        if (productId != -1 && user != null && user.getUserId() != null) {
            long timpStamp = System.currentTimeMillis();
            String content = "{\"productId\":" + productId + ",\"customerId\":"
                    + user.getUserId() + ",\"createTime\":" + timpStamp + "}";
            String longUrl = URLPREFIX + content + URLSUFFIX;
            String shortUrl = ShortNetAddress.getShortURL(longUrl);
            BitMatrix qRcodeImg = QRCodeUtil.generateQRCodeStream(shortUrl,
                    response);
            try {
                MatrixToImageWriter.writeToStream(qRcodeImg, "png",
                        response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
